package com.starblink.basic.style.view.indicator;

import static com.blankj.utilcode.util.SizeUtils.dp2px;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import com.starblink.basic.style.R;
import com.youth.banner.indicator.BaseIndicator;


/**
 * Drawable指示器
 */
public class GuangDrawableIndicator extends BaseIndicator {
    private Bitmap normalBitmap;
    private Bitmap selectedBitmap;

    /**
     * 实例化Drawable指示器 ，也可以通过自定义属性设置
     *
     * @param context
     */

    public GuangDrawableIndicator(Context context) {
        this(context, null);
    }

    public GuangDrawableIndicator(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GuangDrawableIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
//        normalBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_indict_normal);
//        selectedBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_indict_sel);
        normalBitmap = drawableToBitmap(getResources().getDrawable(R.drawable.sp_stroke_gray_indicat));
        selectedBitmap = drawableToBitmap(getResources().getDrawable(R.drawable.sp_stroke_gray_indicat_sel));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int count = config.getIndicatorSize();
        if (count <= 1) {
            return;
        }
        setMeasuredDimension(normalBitmap.getWidth() * (count - 1) + selectedBitmap.getWidth() + config.getIndicatorSpace() * (count - 1),
                Math.max(normalBitmap.getHeight(), selectedBitmap.getHeight()));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int count = config.getIndicatorSize();
        if (count <= 1 || normalBitmap == null || selectedBitmap == null) {
            return;
        }

        float left = 0;
        for (int i = 0; i < count; i++) {
            canvas.drawBitmap(config.getCurrentPosition() == i ? selectedBitmap : normalBitmap, left, 0, mPaint);
            left += (config.getCurrentPosition() == i ? selectedBitmap.getWidth() : normalBitmap.getWidth()) + dp2px(5f);
        }
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }

}
